import lib.system.FlowProcessor;

var flowProcessor=FlowProcessor.getInstance();

var currentBlockNum;
var timestampArray:Array;
var baseTime:Number=0;
// var blockStartTime:Number;
var recordFlag:Boolean;

function record(rd:Boolean)
{
	recordFlag=rd;
	if (recordFlag)
	{
		// check resume or start
		if (baseTime>0)
		{
			// resume
			Packages.modula.MicrophoneDevice.resume(Packages.task.Composition.audioId);

			status="recording";
			baseTime=getTimer()-timestampArray[timestampArray.length-1].time;
		}
		else 
		{
			// start
			// startRecord(Packages.task.Composition.audioId);
			Packages.modula.MicrophoneDevice.publish(Packages.task.Composition.audioId, "record");

			status="recording";
			timestampArray=new Array();
			currentBlockNum=0;
			baseTime=getTimer();
			// blockStartTime=0;	// currentTime - baseTime
		}
	}
	else 
	{
		// pause or stop (flush while publish)
		// Packages.modula.MicrophoneDevice.pause(Packages.task.Composition.audioId);
		Packages.modula.MicrophoneDevice.close();

		status="pause";
		Packages.modula.TxtReader.switchBlock(0, true);
		// displayTimestampArray();
		generateTimestampData();
	}
}

function addTimeStamp(currentBlocklength:Number, nextBlockNum:Number)
{
	// if (status!="recording") return;
	timestampArray[currentBlockNum]=new Object();
	// timestampArray[currentBlockNum].length=currentBlocklength;
	timestampArray[currentBlockNum].time=getTimer()-baseTime;

	currentBlockNum=nextBlockNum;
}

function generateTimestampData()
{
	var pointStr:String="";
	for (var i=0; i<timestampArray.length; i++)
	{
		pointStr+=String(Math.floor(timestampArray[i].time/1000));
		if (i<timestampArray.length-1)
		{
			pointStr+=";";
		}
		else Packages.task.Composition.processData.duration=Math.floor(timestampArray[i].time/1000);
	}
	trace("pointStr: "+pointStr);
	Packages.task.Composition.processData.timestamp=pointStr;
}

function displayTimestampArray()
{
	var pointStr:String="";
	for (var i=0; i<timestampArray.length; i++)
	{
		trace("Block: "+i+"; length: "+timestampArray[i].length+"; time: "+timestampArray[i].time);
		pointStr+=Math.floor(timestampArray[i].time/1000)+":"+timestampArray[i].length+";";
	}
	trace("pointStr: "+pointStr);
}

function clear()
{
	delete timestampArray;
	baseTime=0;
	delete recordFlag;
}

/*function complete()
{
	// generate the mlv sync file
	var syncFile:String=generateMLVbyWork();
	trace("syncFile: "+syncFile);
	// generate the syncId

	// clear the processing data
	Packages.task.Composition.clear();
	clear();
}*/

function generateMLVbyWork():String
{
	var mlvString:String="";
	var duration:Number=Packages.task.Composition.processData.duration;
	var blockMin=Packages.task.Composition.readerSettings.block.size?Packages.task.Composition.readerSettings.block.size:100;
	var contentPath=Packages.task.Composition.contentId;
	var uuidIndex=contentPath.indexOf("uuid");
	var atIndex=contentPath.indexOf("&");
	var bookUUID=contentPath.substring(uuidIndex+5, atIndex);
	mlvString+="<mlv duration='"+duration+"' name='MLV' info='designed by blue night'>";
	mlvString+="<resource>";
	mlvString+="<ext name='txtreader' uri='app/txtReader.swf'/>";
	mlvString+="<ext name='txtsync' uri='app/txtSync.swf'/>";
	mlvString+="<txtreader name='chapter_c1' uri='$[book:"+bookUUID+"]'/>";
	mlvString+="<txtsync name='chapter_s1' size='-1'>";
	mlvString+="<sync blockMin='"+blockMin+"'>";
	mlvString+="<point>"+Packages.task.Composition.processData.timestamp+"</point>";
	mlvString+="</sync>";
	mlvString+="</txtsync>";
	mlvString+="<$[format] name='chapter_a1' uri='$[audio:"+Packages.task.Composition.filteredAudioId+"]'/>";
	mlvString+="</resource>";
	mlvString+="<playback>";
	mlvString+="<clip name='chapter_a1_c1' signpost='1' length='"+duration+"' layer='10' ref='chapter_a1'/>";
	mlvString+="<clip name='chapter_c1_c1' signpost='1' length='"+duration+"' layer='5' ref='chapter_c1'/>";
	mlvString+="<clip name='chapter_s1_c1' signpost='1' length='"+duration+"' layer='15' ref='chapter_s1' option='1'/>";
	mlvString+="</playback>";
	mlvString+="</mlv>";

	return mlvString;
}

function publish()
{
	Packages.system.MLF.addListener("noTick", this);
	flowProcessor.regRules("PublishReadingMaterial");

	flowProcessor.regEvent("onPublishText", Packages.task.Composition.contentId);
	Packages.system.MLF.addListener("onPublishText", this);

	flowProcessor.regEvent("onPublishMP3", Packages.task.Composition.filteredAudioId);
	Packages.system.MLF.addListener("onPublishMP3", this);

	flowProcessor.regEvent("onPublishSync", null);
	Packages.system.MLF.addListener("onPublishSync", this);

	flowProcessor.regEvent("onPublishZip", null);
	Packages.system.MLF.addListener("onPublishZip", this);

	flowProcessor.launchEvent();
}

function onPublishText(obj)
{
	Packages.system.MLF.removeListener("onPublishText", this);
	trace("onPublishText: "+obj.param);
	Packages.system.MLF.dispatchMessage({type:"onPublishReadingMaterial", scope:"txt", result:"Done"});
	flowProcessor.launchEvent();
}

function onPublishMP3(obj)
{
	Packages.system.MLF.removeListener("onPublishMP3", this);
	trace("onPublishMP3: "+obj.param);
	var contentPath=Packages.task.Composition.contentId;
	var uuidIndex=contentPath.indexOf("uuid");
	var atIndex=contentPath.indexOf("&");
	var bookUUID=contentPath.substring(uuidIndex+5, atIndex);
	// trace("bookUUID: "+bookUUID);
	var item=new Object();
	item.type="saveAudio";
	item.param=new Object();
	item.param.uuid=obj.param;
	item.param.bookUuid=bookUUID;
	item.param.recorder=Packages.task.Composition.username;
	item.param.duration=Packages.task.Composition.processData.duration;
	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		trace("saveAudio.obj.returnCode: "+res.returnCode);
		trace("saveAudio.obj.returnObj: "+res.returnObj);
		var rst:String;
		if (res.returnCode==0) rst="Done";
		else rst="Failed";
		Packages.task.Composition.filteredAudioId=res.returnObj;
		Packages.system.MLF.dispatchMessage({type:"onPublishReadingMaterial", scope:"mp3", result:rst});
		this.owner.flowProcessor.launchEvent();
	}   
	Packages.system.MLF.rtmpCaller(item);
}

function onPublishSync(obj)
{
	Packages.system.MLF.removeListener("onPublishSync", this);
	// trace("onPublishSync: "+obj.param);
	
	var item=new Object();
	item.type="generateUuid";
	item.param=new Object();
	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		trace("generateSyncId.onResult: "+res.returnObj);
		if (res.returnObj!=null)
		{
			this.owner.publishSyncFile(res.returnObj);
		}
	}	
	Packages.system.MLF.rtmpCaller(item);
}

function onPublishZip(obj)
{
	Packages.system.MLF.removeListener("onPublishZip", this);
	addDeployProgressListener();

	if (Packages.task.Composition.filteredAudioId==null)
	{
		Packages.system.MLF.dispatchMessage({type:"onPublishReadingMaterial", scope:"zip", result:"Failed"});
		flowProcessor.launchEvent();
		return;
	}
	
	var item=new Object();
	item.type="deployReading";
	item.param=new Object();
	item.param.audioUuid=Packages.task.Composition.filteredAudioId;
	item.param.deployType="swf/packaged";
	item.param.vendor="Nokia";
	item.param.model="N95";

	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		trace("deployReading.obj.returnCode: "+res.returnCode+" returnObj:"+res.returnObj);
		// Packages.system.MLF.dispatchMessage({type:"onPublishReadingMaterial", scope:"zip", result:"Done"});
		// this.owner.flowProcessor.launchEvent();
	}	
	Packages.system.MLF.rtmpCaller(item);
}

function addDeployProgressListener()
{
	var nc=Packages.system.MLF.accessDefaultConnection();
	nc.owner=this;
	if (nc.isConnected==true)
	{
		// trace("register onDeployProgresss...");
		nc.onDeployProgress=function(inputFileName:String, percentage:Number) 
		{
			 trace("onDeployProgress...input:"+inputFileName+" percentage:"+percentage);
			 if (percentage==100)
			 {
				Packages.system.MLF.dispatchMessage({type:"onPublishReadingMaterial", scope:"zip", result:"Done"});
				this.owner.flowProcessor.launchEvent();
			 }
		}
	}
}

function deployWebSite()
{	
	if (Packages.task.Composition.filteredAudioId==null)
	{
		Packages.system.MLF.dispatchMessage({type:"onPublishReadingMaterial", scope:"web", result:"Failed"});
		flowProcessor.launchEvent();
		return;
	}
	
	var item=new Object();
	item.type="deployReading";
	item.param=new Object();
	item.param.audioUuid=Packages.task.Composition.filteredAudioId;
	item.param.deployType="mp3/unpackaged";
	item.param.vendor="Nokia";
	item.param.model="N95";

	item.result=new Object();
	item.result.owner=this;
	item.result.onResult=function(res)
	{
		trace("deployReading.obj.returnCode: "+res.returnCode+" returnObj:"+res.returnObj);
		Packages.system.MLF.dispatchMessage({type:"onPublishReadingMaterial", scope:"web", result:"Done"});
		this.owner.flowProcessor.launchEvent();

		//
		var recentRecord=Packages.system.MLF.scanDictionary(Packages.components.ReadingRecorder.recorderMain, "Recent Recording");
		Packages.components.ReadingPlayer.addPlayItem({name:recentRecord, sync:Packages.system.Util.getHttpBaseUrl()+"/download?uuid="+res.returnObj+"&type=2&subtype=1000"});
	}	
	Packages.system.MLF.rtmpCaller(item);
}

function publishSyncFile(uuid:String)
{	
	var rst_lv:LoadVars=new LoadVars();
	rst_lv.owner=this;
	rst_lv.onLoad=function(success)
	{
		trace("onLoad: "+success);
		this.owner.deployWebSite();
	}
	var sync_lv:LoadVars=new LoadVars();
	sync_lv.uuid=uuid;
	sync_lv.content=generateMLVbyWork();
	sync_lv.audioUuid=Packages.task.Composition.filteredAudioId;
	sync_lv.type=5;
	sync_lv.sendAndLoad(Packages.system.Util.getHttpBaseUrl()+"/upload", rst_lv);

	// trace(sync_lv.toString());
}

function noTick(obj)
{
	Packages.system.MLF.removeListener("noTick", this);
	trace("noTick");
}